[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  19. import { Comments } from '~/components/Comments';
  20. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  21. // import { useTranslation } from '~/i18n';
  22. import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  23. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  24. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  25. import type { CrowiRequest } from '~/interfaces/crowi-request';
  26. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  27. // import { useRendererSettings } from '~/stores/renderer';
  28. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  29. import type { EditorConfig } from '~/interfaces/editor-settings';
  30. import type { RendererConfig } from '~/interfaces/services/renderer';
  31. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  32. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  33. import type { PageModel, PageDocument } from '~/server/models/page';
  34. import type { PageRedirectModel } from '~/server/models/page-redirect';
  35. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  36. import { useEditingMarkdown } from '~/stores/editor';
  37. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  38. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  39. import { useRedirectFrom } from '~/stores/page-redirect';
  40. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  41. import {
  42. useSelectedGrant,
  43. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  44. } from '~/stores/ui';
  45. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  46. import loggerFactory from '~/utils/logger';
  47. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  48. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  49. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  50. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  51. import { BasicLayoutWithEditorMode } from '../components/Layout/BasicLayout';
  52. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  53. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  54. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  55. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  56. import {
  57. useCurrentUser,
  58. useIsLatestRevision,
  59. useIsForbidden, useIsNotFound, useIsSharedUser,
  60. useIsEnabledStaleNotification, useIsIdenticalPath,
  61. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  62. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  63. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  64. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  65. useIsSlackConfigured, useRendererConfig,
  66. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useCustomizedLogoSrc, useIsContainerFluid,
  67. } from '../stores/context';
  68. import { NextPageWithLayout } from './_app.page';
  69. import {
  70. CommonProps, getNextI18NextConfig, getServerSideCommonProps, generateCustomTitle,
  71. } from './utils/commons';
  72. declare global {
  73. // eslint-disable-next-line vars-on-top, no-var
  74. var globalEmitter: EventEmitter;
  75. }
  76. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  77. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  78. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  79. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  80. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  81. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  82. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  83. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  84. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  85. const logger = loggerFactory('growi:pages:all');
  86. const {
  87. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  88. } = pagePathUtils;
  89. const { removeHeadingSlash } = pathUtils;
  90. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  91. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  92. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  93. {
  94. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  95. return v?.data != null
  96. && v?.data.toObject != null
  97. && v?.meta != null
  98. && isIPageInfoForEntity(v.meta);
  99. },
  100. serialize: (v) => {
  101. return {
  102. data: superjson.stringify(v.data.toObject()),
  103. meta: superjson.stringify(v.meta),
  104. };
  105. },
  106. deserialize: (v) => {
  107. return {
  108. data: superjson.parse(v.data),
  109. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  110. };
  111. },
  112. },
  113. 'IPageToShowRevisionWithMetaTransformer',
  114. );
  115. const IdenticalPathPage = (): JSX.Element => {
  116. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  117. return <IdenticalPathPage />;
  118. };
  119. const PutbackPageModal = (): JSX.Element => {
  120. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  121. return <PutbackPageModal />;
  122. };
  123. type Props = CommonProps & {
  124. currentUser: IUser,
  125. pageWithMeta: IPageToShowRevisionWithMeta | null,
  126. // pageUser?: any,
  127. redirectFrom?: string;
  128. // shareLinkId?: string;
  129. isLatestRevision?: boolean,
  130. isIdenticalPathPage?: boolean,
  131. isForbidden: boolean,
  132. isNotFound: boolean,
  133. isNotCreatablePage: boolean,
  134. // isAbleToDeleteCompletely: boolean,
  135. templateTagData?: string[],
  136. templateBodyData?: string,
  137. isSearchServiceConfigured: boolean,
  138. isSearchServiceReachable: boolean,
  139. isSearchScopeChildrenAsDefault: boolean,
  140. isSlackConfigured: boolean,
  141. // isMailerSetup: boolean,
  142. isAclEnabled: boolean,
  143. // hasSlackConfig: boolean,
  144. drawioUri: string | null,
  145. hackmdUri: string,
  146. noCdn: string,
  147. // highlightJsStyle: string,
  148. isAllReplyShown: boolean,
  149. isContainerFluid: boolean,
  150. editorConfig: EditorConfig,
  151. isEnabledStaleNotification: boolean,
  152. isEnabledAttachTitleHeader: boolean,
  153. // isEnabledLinebreaks: boolean,
  154. // isEnabledLinebreaksInComments: boolean,
  155. adminPreferredIndentSize: number,
  156. isIndentSizeForced: boolean,
  157. disableLinkSharing: boolean,
  158. rendererConfig: RendererConfig,
  159. // UI
  160. userUISettings?: IUserUISettings
  161. // Sidebar
  162. sidebarConfig: ISidebarConfig,
  163. };
  164. const Page: NextPageWithLayout<Props> = (props: Props) => {
  165. // const { t } = useTranslation();
  166. const router = useRouter();
  167. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  168. // register global EventEmitter
  169. if (isClient() && window.globalEmitter == null) {
  170. window.globalEmitter = new EventEmitter();
  171. }
  172. // commons
  173. useEditorConfig(props.editorConfig);
  174. useCsrfToken(props.csrfToken);
  175. useCustomizedLogoSrc(props.customizedLogoSrc);
  176. // UserUISettings
  177. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  178. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  179. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  180. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  181. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  182. // page
  183. useIsLatestRevision(props.isLatestRevision);
  184. useIsContainerFluid(props.isContainerFluid);
  185. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  186. useIsForbidden(props.isForbidden);
  187. useIsNotFound(props.isNotFound);
  188. useRedirectFrom(props.redirectFrom);
  189. useIsSharedUser(false); // this page cann't be routed for '/share'
  190. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  191. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  192. useIsSearchPage(false);
  193. useTemplateTagData(props.templateTagData);
  194. useTemplateBodyData(props.templateBodyData);
  195. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  196. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  197. useIsSearchServiceReachable(props.isSearchServiceReachable);
  198. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  199. useIsSlackConfigured(props.isSlackConfigured);
  200. // useIsMailerSetup(props.isMailerSetup);
  201. useIsAclEnabled(props.isAclEnabled);
  202. // useHasSlackConfig(props.hasSlackConfig);
  203. useDrawioUri(props.drawioUri);
  204. useHackmdUri(props.hackmdUri);
  205. // useNoCdn(props.noCdn);
  206. useDefaultIndentSize(props.adminPreferredIndentSize);
  207. useIsIndentSizeForced(props.isIndentSizeForced);
  208. useDisableLinkSharing(props.disableLinkSharing);
  209. useRendererConfig(props.rendererConfig);
  210. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  211. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  212. useIsAllReplyShown(props.isAllReplyShown);
  213. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  214. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  215. const { pageWithMeta, userUISettings } = props;
  216. const pageId = pageWithMeta?.data._id;
  217. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  218. useCurrentPageId(pageId ?? null);
  219. useRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  220. useRemoteRevisionId(pageWithMeta?.data.revision?._id);
  221. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  222. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  223. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  224. useCurrentPathname(props.currentPathname);
  225. useSWRxCurrentPage(undefined, pageWithMeta?.data ?? null); // store initial data
  226. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  227. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  228. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  229. useSetupGlobalSocket();
  230. useSetupGlobalSocketForPage(pageId);
  231. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName();
  232. const shouldRenderPutbackPageModal = pageWithMeta != null
  233. ? _isTrashPage(pageWithMeta.data.path)
  234. : false;
  235. // sync grant data
  236. useEffect(() => {
  237. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  238. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  239. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  240. useEffect(() => {
  241. const decodedURI = decodeURI(window.location.pathname);
  242. if (isClient() && decodedURI !== props.currentPathname) {
  243. const { search, hash } = window.location;
  244. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  245. }
  246. }, [props.currentPathname, router]);
  247. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  248. const title = generateCustomTitle(props, 'GROWI');
  249. return (
  250. <>
  251. <Head>
  252. <title>{title}</title>
  253. </Head>
  254. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  255. <header className="py-0 position-relative">
  256. <div id="grw-subnav-container">
  257. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  258. </div>
  259. </header>
  260. <div className="d-edit-none">
  261. <GrowiSubNavigationSwitcher />
  262. </div>
  263. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  264. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  265. <div className="flex-grow-1">
  266. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  267. <div id="content-main" className="content-main grw-container-convertible">
  268. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  269. { !props.isIdenticalPathPage && (
  270. <>
  271. <PageAlerts />
  272. { props.isForbidden && <ForbiddenPage /> }
  273. { props.isNotCreatablePage && <NotCreatablePage />}
  274. { !props.isForbidden && !props.isNotCreatablePage && <DisplaySwitcher />}
  275. <PageStatusAlert />
  276. </>
  277. ) }
  278. </div>
  279. </div>
  280. </div>
  281. { !props.isIdenticalPathPage && !props.isNotFound && (
  282. <footer className="footer d-edit-none">
  283. { pageWithMeta != null && pagePath != null && !isTopPagePath && (
  284. <Comments pageId={pageId} pagePath={pagePath} revision={pageWithMeta.data.revision} />
  285. ) }
  286. { pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path) && (
  287. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  288. ) }
  289. <CurrentPageContentFooter />
  290. </footer>
  291. )}
  292. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  293. </div>
  294. </>
  295. );
  296. };
  297. Page.getLayout = function getLayout(page) {
  298. return (
  299. <>
  300. <DrawioViewerScript />
  301. <BasicLayoutWithEditorMode>
  302. {page}
  303. </BasicLayoutWithEditorMode>
  304. <UnsavedAlertDialog />
  305. <DescendantsPageListModal />
  306. <DrawioModal />
  307. <HandsontableModal />
  308. </>
  309. );
  310. };
  311. function getPageIdFromPathname(currentPathname: string): string | null {
  312. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  313. }
  314. class MultiplePagesHitsError extends ExtensibleCustomError {
  315. pagePath: string;
  316. constructor(pagePath: string) {
  317. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  318. this.pagePath = pagePath;
  319. }
  320. }
  321. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  322. const { model: mongooseModel } = await import('mongoose');
  323. const req: CrowiRequest = context.req as CrowiRequest;
  324. const { crowi } = req;
  325. const { revisionId } = req.query;
  326. const Page = crowi.model('Page') as PageModel;
  327. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  328. const { pageService } = crowi;
  329. let currentPathname = props.currentPathname;
  330. const pageId = getPageIdFromPathname(currentPathname);
  331. const isPermalink = _isPermalink(currentPathname);
  332. const { user } = req;
  333. if (!isPermalink) {
  334. // check redirects
  335. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  336. if (chains != null) {
  337. // overwrite currentPathname
  338. currentPathname = chains.end.toPath;
  339. props.currentPathname = currentPathname;
  340. // set redirectFrom
  341. props.redirectFrom = chains.start.fromPath;
  342. }
  343. // check whether the specified page path hits to multiple pages
  344. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  345. if (count > 1) {
  346. throw new MultiplePagesHitsError(currentPathname);
  347. }
  348. }
  349. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  350. const page = pageWithMeta?.data as unknown as PageDocument;
  351. // add user to seen users
  352. if (page != null && user != null) {
  353. await page.seen(user);
  354. }
  355. // populate & check if the revision is latest
  356. if (page != null) {
  357. page.initLatestRevisionField(revisionId);
  358. await page.populateDataToShowRevision();
  359. props.isLatestRevision = page.isLatestRevision();
  360. }
  361. if (page == null && user != null) {
  362. const templateData = await Page.findTemplate(props.currentPathname);
  363. if (templateData != null) {
  364. props.templateTagData = templateData.templateTags as string[];
  365. props.templateBodyData = templateData.templateBody as string;
  366. }
  367. }
  368. props.pageWithMeta = pageWithMeta;
  369. }
  370. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  371. const { model: mongooseModel } = await import('mongoose');
  372. const req = context.req as CrowiRequest<IUserHasId & any>;
  373. const { user } = req;
  374. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  375. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  376. if (userUISettings != null) {
  377. props.userUISettings = userUISettings.toObject();
  378. }
  379. }
  380. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  381. const req: CrowiRequest = context.req as CrowiRequest;
  382. const { crowi } = req;
  383. const Page = crowi.model('Page') as PageModel;
  384. const { currentPathname } = props;
  385. const pageId = getPageIdFromPathname(currentPathname);
  386. const isPermalink = _isPermalink(currentPathname);
  387. const page = props.pageWithMeta?.data;
  388. if (props.isIdenticalPathPage) {
  389. // TBD
  390. }
  391. else if (page == null) {
  392. props.isNotFound = true;
  393. props.isNotCreatablePage = !isCreatablePage(currentPathname);
  394. // check the page is forbidden or just does not exist.
  395. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  396. props.isForbidden = count > 0;
  397. }
  398. else {
  399. props.isNotFound = page.isEmpty;
  400. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  401. if (isPermalink && page.isEmpty) {
  402. props.currentPathname = page.path;
  403. }
  404. // /path/to/page ==> /62a88db47fed8b2d94f30000
  405. if (!isPermalink && !page.isEmpty) {
  406. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  407. if (!isToppage) {
  408. props.currentPathname = `/${page._id}`;
  409. }
  410. }
  411. }
  412. }
  413. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  414. // const req: CrowiRequest = context.req as CrowiRequest;
  415. // const { crowi } = req;
  416. // const UserModel = crowi.model('User');
  417. // if (isUserPage(props.currentPagePath)) {
  418. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  419. // if (user != null) {
  420. // props.pageUser = JSON.stringify(user.toObject());
  421. // }
  422. // }
  423. // }
  424. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  425. const req: CrowiRequest = context.req as CrowiRequest;
  426. const { crowi } = req;
  427. const {
  428. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  429. } = crowi;
  430. props.isSearchServiceConfigured = searchService.isConfigured;
  431. props.isSearchServiceReachable = searchService.isReachable;
  432. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  433. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  434. // props.isMailerSetup = mailService.isMailerSetup;
  435. props.isAclEnabled = aclService.isAclEnabled();
  436. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  437. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  438. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  439. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  440. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  441. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  442. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  443. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  444. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  445. props.editorConfig = {
  446. upload: {
  447. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  448. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  449. },
  450. };
  451. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  452. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  453. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  454. props.rendererConfig = {
  455. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  456. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  457. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  458. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  459. plantumlUri: process.env.PLANTUML_URI ?? null,
  460. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  461. // XSS Options
  462. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  463. tagWhiteList: crowi.xssService.getTagWhiteList(),
  464. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  465. // XSS: rehype-sanitize options
  466. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  467. };
  468. props.sidebarConfig = {
  469. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  470. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  471. };
  472. }
  473. /**
  474. * for Server Side Translations
  475. * @param context
  476. * @param props
  477. * @param namespacesRequired
  478. */
  479. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  480. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  481. props._nextI18Next = nextI18NextConfig._nextI18Next;
  482. }
  483. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  484. const req = context.req as CrowiRequest<IUserHasId & any>;
  485. const { user } = req;
  486. const result = await getServerSideCommonProps(context);
  487. // check for presence
  488. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  489. if (!('props' in result)) {
  490. throw new Error('invalid getSSP result');
  491. }
  492. const props: Props = result.props as Props;
  493. if (props.redirectDestination != null) {
  494. return {
  495. redirect: {
  496. permanent: false,
  497. destination: props.redirectDestination,
  498. },
  499. };
  500. }
  501. if (user != null) {
  502. props.currentUser = user.toObject();
  503. }
  504. try {
  505. await injectPageData(context, props);
  506. }
  507. catch (err) {
  508. if (err instanceof MultiplePagesHitsError) {
  509. props.isIdenticalPathPage = true;
  510. }
  511. else {
  512. throw err;
  513. }
  514. }
  515. await injectUserUISettings(context, props);
  516. await injectRoutingInformation(context, props);
  517. injectServerConfigurations(context, props);
  518. await injectNextI18NextConfigurations(context, props, ['translation']);
  519. return {
  520. props,
  521. };
  522. };
  523. export default Page;